import {Component,  OnInit} from "@angular/core";
import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService, UploadFile} from "ng-zorro-antd";
import {HttpServcie} from "../../../service/http.service";
import {TrainingPlanDetailBean} from "../bean/trainingPlanDetail.bean";
import {Config} from "../../../service/config";
import {TrainingPlanBean} from "../bean/trainingPlan.bean";
import * as moment from "moment";

@Component({
  selector: "trainingPlan-result-page",
  templateUrl: "trainingPlan-result.html",
  styleUrls: ["trainingPlan-result.scss"]
})

export class TrainingPlanResult {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService
  ) { }
  trainingPlanDetail : TrainingPlanDetailBean = new TrainingPlanDetailBean();
  partyTypes = Config.PARTY_TYPE;
  planStatus = Config.PLAN_STATUS;
  config = Config;
  partyType : string = "";
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;
  startDate : string = "";
  endDate : string = "";
  planName : string = "";
  planType : string = "";
  //返回的集合
  dataList : any = [];
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  total : number;
  updateData: any = {};
  //文件上传
  trainingPhotoFileList : UploadFile[] = []; //培训现场照片
  checkInTableFileList : UploadFile[] = []; //签到表
  summaryStatementFileList : UploadFile[] = []; //考核汇总表
  isVisible : boolean = false;
  uploadType : any;

  ngOnInit(){
    this.partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
    this.trainingPlanDetail.pageSize = 10;
    this.trainingPlanDetail.currentPage = 1;
    this.query();
  }
  query(){
    if(this.trainingPlanDetail.startDate){
      this.trainingPlanDetail.startDate = moment(this.trainingPlanDetail.startDate).format("YYYYMMDD");
    }
    if(this.trainingPlanDetail.endDate){
      this.trainingPlanDetail.endDate = moment(this.trainingPlanDetail.endDate).format("YYYYMMDD");
    }
    this.trainingPlanDetail.partyId = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.httpService.queryTrainingPlanDetail(this.trainingPlanDetail).subscribe(data => {
      if (data.status == "200") {
        this.dataList = data.data.list;
        this.total = data.data.total;
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  //打开上传模态框 1：培训现场照片；2：培训签到表；3：考核汇总表；
  uploadFile(data, type) {
    this.trainingPhotoFileList = [];
    this.checkInTableFileList = [];
    this.summaryStatementFileList = [];
    this.updateData = data;
    this.isVisible = true;
    this.uploadType = type;
    if (type == 1) {
      if (data.trainingPhoto) {
        (data.trainingPhoto + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111000,
            name: ele,
            type: 'image/png',
            response: {
              data: ele
            }
          }
          this.trainingPhotoFileList.push(file);
        })
      }
    }
    if (type == 2) {
      if (data.checkInTable) {
        (data.checkInTable + "").split(',').forEach(ele => {
          let file: UploadFile = {
            "thumbUrl": this.config.IP + this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111000,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.checkInTableFileList.push(file);
        })
      }
    }
    if (type == 3) {
      if (data.summaryStatement) {
        (data.summaryStatement + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP + this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111000,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.summaryStatementFileList.push(file);
        })
      }
    }
  }

  nzRemoveFile = (file: UploadFile) => {
    this.httpService.deleteUpload(file["response"]["data"]).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }

        if (this.uploadType == 1) {
          if (this.trainingPhotoFileList.length == 1) {
            this.trainingPhotoFileList = [];
            return;
          }
          this.trainingPhotoFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.trainingPhotoFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 2) {
          if (this.checkInTableFileList.length == 1) {
            this.checkInTableFileList = [];
            return;
          }
          this.checkInTableFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.checkInTableFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 3) {
          if (this.summaryStatementFileList.length == 1) {
            this.summaryStatementFileList = [];
            return;
          }
          this.summaryStatementFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.summaryStatementFileList.splice(index, 1);
            }
          });
        }

      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  };

  uploadChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "上传成功");
      }
      // Get this url from response in real world.
    }
  }

//上传文件完成后的回调
  nzChangeFile(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      if (this.uploadType == 1) {
        this.trainingPhotoFileList.forEach(element => {
          //alert(JSON.stringify(element));
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

      if (this.uploadType == 2) {
        this.checkInTableFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

      if (this.uploadType == 3) {
        this.summaryStatementFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }
    }
  }
  //上传完了之后 提交数据
  updateUpload() {
    if (this.uploadType == 1) {
      let param = {
        id: this.updateData.id,
        trainingPhoto : null
      }
      let list = [];
      this.trainingPhotoFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.trainingPhoto = list.join(',')
      this.httpService.updateTrainingPhoto(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.trainingPhotoFileList = [];
          this.updateData.trainingPhoto = param.trainingPhoto;
          this.changePlanStatus(this.updateData);
          this.query();
        }
      });
    }
    if (this.uploadType == 2) {
      let param = {
        id: this.updateData.id,
        checkInTable : null
      }
      let list = [];
      this.checkInTableFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.checkInTable = list.join(',');
      this.httpService.updateCheckInTable(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.checkInTableFileList = [];
          this.updateData.checkInTable = param.checkInTable;
          this.changePlanStatus(this.updateData);
          this.query();
        }
      });
    }
    if (this.uploadType == 3) {
      let param = {
        id: this.updateData.id,
        summaryStatement: null
      }
      let list = [];
      this.summaryStatementFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.summaryStatement = list.join(',');
      this.httpService.updateSummaryStatement(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.summaryStatementFileList = [];
          this.updateData.summaryStatement = param.summaryStatement;
          this.changePlanStatus(this.updateData);
          this.query();
        }
      });
    }
  }

  //每次上传判断所有资料,修改计划状态为完成
  changePlanStatus(data){
    const idList: any = [];
    idList.push(data.id);

    let param = {
      ids: idList,
      planStatus : null,
      partyId:JSON.parse(window.localStorage.getItem("user")).partyId,
      // 角色Id
      roleId:JSON.parse(window.localStorage.getItem("user")).roleId,
      // 单位类型
      loggerType:JSON.parse(window.localStorage.getItem("user")).partyType,
      // 用户Id
      loggerUserId:JSON.parse(window.localStorage.getItem("user")).id,
    }
    if(data.trainingPhoto && data.checkInTable && data.summaryStatement){
      param.planStatus = "2";
    }else{
      param.planStatus = "1";
    }

    this.httpService.updateTrainingPlanStatus(param).subscribe(data => {
      if (data["status"] != "200") {
        this._notification.create("error", "错误提示", "修改失败！");
      }
      if (data["status"] === "200") {
        this._notification.create("success", "", "修改成功！");
      }
    });
  }
  //下载
  downloadFile(data, type) {
    //下载前获取对应的计划
    let tempTrainingPlan : TrainingPlanBean = new TrainingPlanBean();
    tempTrainingPlan.id = data.planId;
    this.httpService.queryTrainingPlan(tempTrainingPlan).subscribe(data => {
      if (data.status == "200") {
        tempTrainingPlan = data.data.list[0];
        this.getFile(tempTrainingPlan,type);
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  getFile(tempTrainingPlan,type){
    //培训资料
    if (type == 1) {
      if (!tempTrainingPlan.materials) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = tempTrainingPlan.materials.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '培训资料' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    //签到表
    if (type == 2) {
      if (!tempTrainingPlan.checkInTable) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = tempTrainingPlan.checkInTable.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '签到表' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }

    }
    //培训试卷
    if (type == 3) {
      if (!tempTrainingPlan.testPaper) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = tempTrainingPlan.testPaper.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '培训试卷' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    //考核汇总表
    if (type == 4) {
      if (!tempTrainingPlan.summaryStatement) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = tempTrainingPlan.summaryStatement.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '考核汇总表' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
  }

  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }


  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }
  //分页处理
  nzPageSizeChange(event){
    this.trainingPlanDetail.pageSize = event;
    this.trainingPlanDetail.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.trainingPlanDetail.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.trainingPlanDetail.currentPage = event;
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

}
